package com.kern.service.impl;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.kern.dao.ProductDao;
import com.kern.entity.XProduct;
import com.kern.service.IProductService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by caoshi at 10:36 2021/7/30
 */
@Service
public class ProductServiceImpl implements IProductService {


    @Autowired
    private ProductDao productDao;


    @Override
    public List<XProduct> listAll() {
        return productDao.findAll();
    }

    @Override
    public List<JSONObject> listAllForJSONList() {
        List<XProduct> productList = listAll();
        List<JSONObject> productJSONList = new ArrayList<>();

        for (XProduct xProduct : productList) {
            JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(xProduct));
            productJSONList.add(object);
        }

        return productJSONList;
    }


    @Override
    public Workbook write(String filename, List<XProduct> data, Map<String, String> title) {
        ExcelWriter writer = ExcelUtil.getWriter(filename);

        // 设置表头标题行
        for (Map.Entry<String, String> entry : title.entrySet()) {
            String name = entry.getKey();           // 字段别名
            String alias = entry.getValue();        // 字段名
            writer.addHeaderAlias(name, alias);
        }

        // 写入数据
        writer.write(data);
        Workbook wb = writer.getWorkbook();
        Sheet sheet = wb.getSheetAt(0);
        sheet.setDefaultColumnWidth(15);

        return wb;
    }

    @Override
    public Workbook write2(String filename, List<JSONObject> data, Map<String, String> title) {
        ExcelWriter writer = ExcelUtil.getWriter(filename);

        // 设置表头标题行
        for (Map.Entry<String, String> entry : title.entrySet()) {
            String name = entry.getKey();           // 字段别名
            String alias = entry.getValue();        // 字段名
            writer.addHeaderAlias(name, alias);
        }

        // 写入数据
        writer.write(data);
        Workbook wb = writer.getWorkbook();
        Sheet sheet = wb.getSheetAt(0);
        sheet.setDefaultColumnWidth(15);

        return wb;
    }

    @Override
    public int save(List<XProduct> productList) {
        return productDao.batchInsert(productList);
    }


}
